package com.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.blog.pojo.ThumbsUp;
import com.blog.pojo.User;
import com.blog.service.ThumbsUpService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * Copyright (C), 2022
 * Author: 苏大大
 * Date: 2022-06-09 15:29
 * FileName: ThumbsUpController
 * Description:博客点赞控制层
 */
@RestController
@RequestMapping("/ThumbsUp")
@Slf4j
public class ThumbsUpController extends BaseController {
    @Resource
    private ThumbsUpService thumbsUpService;

    /***
     * 查询用户点赞状态
     * @param blogId
     * @param session
     * @return
     */
    @GetMapping("/{blogId}/{uid}")
    public String selectThumbsUp(@Param("博客ID") @PathVariable("blogId")Long blogId, HttpSession session,
                                 @Param("用户id") @PathVariable("uid") Long uid){
        JSONObject object=new JSONObject();
        if(uid!=null){
            ThumbsUp thumbsUp=thumbsUpService.selectThumbsUp(blogId,uid);
            if(thumbsUp!=null){
                object.put("flag",true);
                object.put("message","用户已点赞!");
            }else{
                object.put("flag",false);
                object.put("message","用户未点赞!");
            }
            return object.toJSONString();
        }
        object.put("flag",false);
        return object.toJSONString();
    }

    /***
     *
     * 用户点赞和取消点赞
     * @param blogId
     * @param uid
     * @return
     */
    @PostMapping("/{blogId}/{uid}")
    public String updateThumbsUp(@Param("博客ID") @PathVariable("blogId")Long blogId,@PathVariable("uid") Long uid){
        JSONObject object=new JSONObject();
        User user=checkUser(uid);
        if(user!=null){
            //查询当前登录用户是否已点赞该博客
            ThumbsUp thumbsUp=thumbsUpService.selectThumbsUp(blogId,user.getUid());
            if(thumbsUp!=null){
                //删除点赞表对应数据
                thumbsUpService.deleteThumbsUp(blogId,user.getUid());
                object.put("flag",false);
                object.put("message","已取消点赞!");
                return object.toJSONString();
            }else{
                //修改博客点赞数量
                ThumbsUp thumbsup=new ThumbsUp();
                thumbsup.setBlogId(blogId).setUid(user.getUid());
                thumbsUpService.insetThumbsUp(thumbsup);
                object.put("message","已点赞!");
                object.put("flag",true);
            }
        }
        return object.toJSONString();
    }
}
